package com.imooc.restful.controller;

import com.imooc.restful.entity.Person;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/restful")
//@CrossOrigin(origins = {"http://localhost:8080"}, allowCredentials = "true")
public class RestfulController {
    @GetMapping("/request")
//    @ResponseBody
    public String doGetRequest() {
        return "{\"message\": \"GET request received\"}";
    }

    @PostMapping("/request/{rid}")
//    @ResponseBody
    public String doPostRequest(@PathVariable("rid") Integer requestId, Person person) {
        System.out.println("Request ID: " + requestId);
        return "{\"message\": \"POST request received\"}";
    }

    @PutMapping("/request")
//    @ResponseBody
    public String doPutRequest(Person person) {
        return "{\"message\": \"PUT request received\"}";
    }

    @DeleteMapping("/request")
//    @ResponseBody
    public String doDeleteRequest() {
        return "{\"message\": \"DELETE request received\"}";
    }


    @GetMapping("/person/{id}")
    public Person findByPersonId(@PathVariable("id") Integer id) {
        Person person = new Person();
        if (id == 1) {
            person.setName("John Doe");
            person.setAge(30);
        } else if (id == 2) {
            person.setName("Jane Smith");
            person.setAge(25);
        } else {
            person.setName("Unknown");
            person.setAge(0);
        }
        return person;
    }

    @GetMapping("/persons")
    public List<Person> findPsersons() {
        List<Person> persons = new ArrayList<>();
        persons.add(new Person("John Doe", 30, new Date()));
        persons.add(new Person("Jane Smith", 25, new Date()));
        return persons;
    }
}
